package com.example.maze;

import java.util.zip.Inflater;

import receivers.CreatRoomRepReceiver;
import receivers.JoinTheGameRepReceiver;
import receivers.LoginRepReceiver;
import receivers.UpdateRoomsListRepReceiver;
import services.CreatRoomService;
import services.JoinTheGameService;
import services.LoginService;
import services.LeaveRoomService;
import services.UpdateRoomsListService;
import tw.edu.tku.im.maze.Room;

import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.content.LocalBroadcastManager;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ScrollView;
import android.widget.Spinner;
import android.widget.TextView;
import android.view.View;

public class LobbyActivity extends Activity {
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_lobby);
      
      //[ 顯示基本資訊
      TextView tv;
      tv= (TextView)this.findViewById(R.id.textview_show_user_name);
      if(ConnectionInfo.name != null) tv.setText("玩家: " + ConnectionInfo.name);      
      tv= (TextView)this.findViewById(R.id.textview_show_user_lv_exp);
      tv.setText("等級: "+ ConnectionInfo.lv + "\t" +
                 "經驗值: "+ ConnectionInfo.exp + "/" +
                  LevelInfo.getNeededExp(ConnectionInfo.lv));
      
      //[ 註冊廣播
      CreatRoomRepReceiver mCreatRoomRepReceiver= new CreatRoomRepReceiver(this);
      LocalBroadcastManager.getInstance(this).registerReceiver(mCreatRoomRepReceiver,
                                                               new IntentFilter(CreatRoomService.BROADCAST_ACTION));
      UpdateRoomsListRepReceiver mUpdateRoomsListRepReceiver= new UpdateRoomsListRepReceiver(this);
      LocalBroadcastManager.getInstance(this).registerReceiver(mUpdateRoomsListRepReceiver,
                                                               new IntentFilter(UpdateRoomsListService.BROADCAST_ACTION));
      JoinTheGameRepReceiver mJoinTheGameRepReceiver= new JoinTheGameRepReceiver(this);
      LocalBroadcastManager.getInstance(this).registerReceiver(mJoinTheGameRepReceiver,
                                                               new IntentFilter(JoinTheGameService.BROADCAST_ACTION));
      
      //[ 供單機測試
      //this.update(new Room[0]);
   }
   // ------------------------------------------------------------
   @Override
   protected void onPause () {
      super.onStop();
      ConnectionInfo.roomListupdateLoop= ConnectionInfo.INTERRUPT;
   }
   // ------------------------------------------------------------
   @Override
   protected void onResume() {
      super.onStart();
      //[ 啟動更新房間列表
      ConnectionInfo.roomListupdateLoop= ConnectionInfo.CONTINUE;
      //[ 確保 Service只有一個
      if(ConnectionInfo.theUpdateService == null) {
         //[ 啟動新的 Service         
         this.startService(new Intent(this, UpdateRoomsListService.class));
      }      
   }
   // ------------------------------------------------------------
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.activity_lobby, menu);
      return true;
   }
   // ------------------------------------------------------------
   public void button_logoutOnClicked(View view) {
      Intent intent= new Intent(this, MainActivity.class);
      this.startActivity(intent);
   }
   // ------------------------------------------------------------   
   MyProgressDialog mProgressDialog;
   public void showMyDialog(String title, String msg) {
      if(mProgressDialog == null) {  // lazy new
         mProgressDialog= new MyProgressDialog(this);
      }
      
      if(!mProgressDialog.hasShowed()) {
         mProgressDialog.show(title,msg);
      } else {
         mProgressDialog.dismiss();
      }
   }   
   public void dismissMyDialog() {
      if(mProgressDialog != null) {
         if(mProgressDialog.hasShowed()) {
            mProgressDialog.dismiss();
         }
      }     
   }
   // -------------------------------------------------- 
   public void button_creatRoomOnClicked(View view) {     
      final Context mContext= this;     
      final AlertDialog.Builder builder= new AlertDialog.Builder(this);
      builder.setTitle("開新遊戲室");           
      
      //[ new layout object from XML file (動態地將 XML Obj新增出來)
      LayoutInflater mInflater= this.getLayoutInflater();
      final ScrollView mScrollView= (ScrollView) mInflater.inflate(R.layout.creat_room_dialog_content, null);
      //]      
      
      builder.setView(mScrollView);
      
      final AlertDialog dialog= builder.create();
      
      final Button okBtn= (Button)mScrollView.findViewById(R.id.Button_ok);
      okBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            //final Intent mIntent= new Intent("services.CreatRoomService");
            final Intent mIntent= new Intent(v.getContext(),CreatRoomService.class);
            //[ 取出控制項內的內容
            String roomName= ((EditText)mScrollView.findViewById(R.id.EditText_roomName)).getText().toString();
            String roomPwd = ((EditText)mScrollView.findViewById(R.id.EditText_roomPwd)).getText().toString();
            String scaleStr= ((Spinner)mScrollView.findViewById(R.id.spinner_mapScale)).getSelectedItem().toString();
            StringBuilder tmpValue= new StringBuilder();
            tmpValue.append(scaleStr.charAt(0));
            if(scaleStr.charAt(1) != ')') tmpValue.append(scaleStr.charAt(1));
            mIntent.putExtra("mapLv", Integer.valueOf(tmpValue.toString()));
            //]
            mIntent.putExtra("userId", ConnectionInfo.id);
            mIntent.putExtra("ticket", ConnectionInfo.ticket);
            mIntent.putExtra("roomName", roomName);
            mIntent.putExtra("roomPwd", roomPwd);
            mIntent.putExtra("mode"  , 0); // 0:合作模式 1:競爭模式
             
            ConnectionInfo.roomName= roomName;
            ConnectionInfo.mapLv   = Integer.valueOf(tmpValue.toString());
            ((LobbyActivity)mContext).showMyDialog("","與伺服器連線中..");
            v.getContext().startService(mIntent);
         }
      });
      final Button cancelBtn= (Button)mScrollView.findViewById(R.id.Button_cancel);
      cancelBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View v) {
            dialog.dismiss();
         }
      });
      dialog.show();
   }
   // ------------------------------------------------------------      
   public void showMsgDialog(String externalStrResourseId) {
      //[ 系統訊息視窗
      try {
         AlertDialog.Builder builder = new AlertDialog.Builder(this);
         builder.setPositiveButton(R.string.dialog_ok_ch, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
               // User clicked OK button
            }
         });         
         //builder.setMessage(externalStrResourseId);
         builder.setMessage(externalStrResourseId);
         AlertDialog dialog = builder.create();
         if(dialog==null) MyLog.d("dialog==null", getClass().getName(), 45);
         dialog.show();
         MyLog.d("errorHandler6", getClass().getName(), 50); 
      } catch(Exception e) {
         MyLog.d("errorHandler7", e.getMessage(), 50); 
      }      
   }
   // --------------------------------------------------
   private int parseRoomId(String roomInfo) {      
      StringBuilder idStr= new StringBuilder();
      boolean reading= false;
      for(int i=0; i<roomInfo.length(); i++) {
//         android.util.Log.d("DebugMsg", roomInfo.charAt(i)+"");
         if(roomInfo.charAt(i) == '[') {            
            reading= true;
            continue;
         } 
         if(roomInfo.charAt(i) == ']') {
            reading= false;
            continue;
         }          
         if(reading) {
            idStr.append(roomInfo.charAt(i));
         } 
      } 
      return Integer.valueOf(idStr.toString());
   }   
   
   //[ callback for Receiver
   public void update(Room[] rooms) {
android.util.Log.d("DebugMsg","roomList updating");      
      if(rooms != null) {
         String[] mItems= new String[rooms.length];  
         //String[] mItems= new String[rooms.length+1]; //: 供單機測試
         Room     room;
         for(int i=0; i<rooms.length; i++) {
            room= rooms[i];
            mItems[i]= "["+room.getRoomID()+"] Map: "+ room.getMapLv()+" "+
                       room.getRoom()+" 室長: "+ room.getHomewoner();
         }
         //mItems[rooms.length]= "[0] Map: 2 歡迎新手~ 室長: Wei";
         ListView mListView = (ListView) findViewById(R.id.listView1);
         mListView.setAdapter(new ArrayAdapter<String>(this,
                              android.R.layout.simple_list_item_1, 
                              mItems));
            
         OnItemClickListener mMessageClickedHandler= new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView parent, View v, int position, long id) {
//                  AlertDialog.Builder builder= new AlertDialog.Builder(v.getContext());
//                  builder.setMessage(((TextView)v).getText().toString());
//                  builder.setPositiveButton("確認", new DialogInterface.OnClickListener() {
//                     public void onClick(DialogInterface dialog, int id) {
//                        // User clicked OK button
//                     }
//                  });
//                  AlertDialog dialog = builder.create();
//                  dialog.show();
   //android.util.Log.d("DebugMsg", ((TextView)v).getText().toString());   
               int roomId= parseRoomId(((TextView)v).getText().toString());
//   android.util.Log.d("DebugMsg", roomId+"");      
               Intent mIntent= new Intent(v.getContext(), JoinTheGameService.class);
               mIntent.putExtra("roomId", roomId);
               ((LobbyActivity)v.getContext()).showMyDialog("","與伺服器連線中..");               
               v.getContext().startService(mIntent);
               
//               Intent intent= new Intent(v.getContext(), RoomActivity.class);
//               v.getContext().startActivity(intent);
            }
         };
         mListView.setOnItemClickListener(mMessageClickedHandler);
      } else {
         ListView mListView = (ListView) findViewById(R.id.listView1);
         mListView.setAdapter(null);
      }
   }
   // --------------------------------------------------
   //[ disable back button
   @Override public void onBackPressed() {}
}
